import { routes } from '@/router/routes'
import { useAppStore } from '@/stores/app'
import wechatOa from './wechat'
import { useUserStore } from '@/stores/user'
import { paramsToStr } from '@/utils/util'
import { SHARE_CODE } from '@/enums/cacheEnums'

export default {
    async onShareAppMessage(res: any) {
        const { getWebsiteConfig } = useAppStore()
        // const path = '/pages/index/index'
        if (res.from === 'button') {
            return {
                title: getWebsiteConfig.shop_name,
                path: await getSharePath()
            }
        }
        if (res.from === 'menu') {
            return {
                title: getWebsiteConfig.shop_name,
                path: await getSharePath()
            }
        }
    },
    // 分享到朋友圈
    onShareTimeline() {
        const { getWebsiteConfig } = useAppStore()
        return {
            title: getWebsiteConfig.shop_name,
            path: '/pages/index/index',
            imageUrl: ''
        }
    },
    onShow() {
        try {
            const pageList = getCurrentPages()
            // 确保 pageList 存在且有页面
            if (!pageList || !pageList.length) return

            const currentPage = pageList[pageList.length - 1]
            // 确保当前页面存在且有 route 属性
            if (!currentPage || !currentPage.route) return

            const pageMate = routes.find((item) => {
                return item.path == `/${currentPage.route}`
            })
            
            // 确保找到了匹配的路由配置
            if (!pageMate || !pageMate.unshare) return

            // #ifdef MP-WEIXIN
            uni.hideShareMenu({
                hideShareItems: []
            })
            // #endif

            // #ifdef H5
            wechatOa.hideMenuItems([
                'menuItem:share:appMessage',
                'menuItem:share:timeline',
                'menuItem:share:qq',
                'menuItem:share:weiboApp',
                'menuItem:share:QZone'
            ])
            // #endif
        } catch (error) {
            console.error('Share onShow error:', error)
        }
    },
    async onLoad(option: any) {
        query = option
    }
}
let query: any = {}

const getSharePath = async () => {
    const pageList = getCurrentPages()
    const currentPage = pageList[pageList.length - 1].route
    let origin = ''
    //#ifdef H5
    origin = `${window.location.origin}/mobile`
    //#endif
    const path = `${origin}/${currentPage}`

    try {
        const userStore = useUserStore()
        if (!userStore?.userInfo?.code) {
            await userStore.getUser()
        }
        if (userStore?.userInfo?.code) {
            query[SHARE_CODE] = userStore?.userInfo?.code
        }
    } catch (error) {
        console.log(error)
    }
    console.log(`${path}${paramsToStr(query)}`)

    return `${path}${paramsToStr(query)}`
}
